<?php

class DefaultController extends FController
{
	public function actionIndex() {
		$category = Yii::app()->request->getParam('category',null);
		$sort = Yii::app()->request->getParam('sort',null);
		
		
		$criteria = new CDbCriteria();
		
		
		$cat = ProductCategories::model()->findByAttributes(array('alias'=>$category));
		
		
		$criteria->condition = 'is_published = :PUBLISHED';
		$criteria->params = array(':PUBLISHED' => Products::PUBLISHED);
		
		switch($sort){
			case "abc":
				$criteria->order = "name asc";
			break;
			case "date":
				$criteria->order = "created desc";
			break;
			case "price":
				$criteria->order = "price desc";
			break;
			default:
				$criteria->order = "name asc";
			break;
		}
		if(!empty($cat)){
			$criteria->with = array('mapcat');
			$criteria->together = true;
			$criteria->addSearchCondition('mapcat.category_id',$cat->id);
		}
		$count = Products::model()->count($criteria);

		$pages = new CPagination($count);

		$pages->setPageSize(Yii::app()->params['postsPerPage']);
		$pages->applyLimit($criteria);
		
		$model = Products::model()->findAll($criteria);
		
		$this->render('index', array(
			"model"			=> !empty($model) ? $model : array(),
			'page_size'		=> Yii::app()->params['postsPerPage'],
			'item_count'	=> $count,
			'sort'	=> $sort,
			'category'	=> $category,
			'pages'			=> $pages
		));
	}
}